import {
  BadRequestException,
  Injectable,
  InternalServerErrorException,
} from "@nestjs/common";
import { InjectRepository } from "@nestjs/typeorm";
import { Repository } from "typeorm";
import { AddSwiperDto, EditSwiperDto, GetSwiperDto } from "../dto/swiper.dto";
import { Swiper } from "/@/entities/operate/Swiper.entity";
import { format } from "/@/utils/moment";
@Injectable()
export class SwiperService {
  constructor(
    @InjectRepository(Swiper)
    private swiperRepository: Repository<Swiper>,
  ) {
    //
  }
  /**
   * 获取轮播列表
   * @param query 字段
   */
  async getSwiperList(query: GetSwiperDto) {
    // 获取参数
    const { pageSize = 20, page = 1, status = "", id } = query;
    try {
      // 获取到QueryBuilder对象 skip take 是为了分页查询 orderBy是排序，DESC降序，
      // where 是查询的条件  swiper.status like :status" 就是模糊查询，不需要完全匹配，swiper.id = :id 需要id相等，也就是完全匹配
      let qb = this.swiperRepository.createQueryBuilder("swiper");
      qb = qb
        .skip(pageSize * (page - 1))
        .take(pageSize)
        .orderBy("swiper.update_at", "DESC")
        .where("swiper.status like :status", { status: "%" + status + "%" });
      if (id) {
        qb = qb.andWhere("swiper.id = :id", { id });
      }
      // 获取数据以及符合条件的总条数
      const data = await qb.getManyAndCount();
      const items = data[0].map((item: any) => {
        // 转化一下时间的格式
        item.update_at = format(item.update_at, "YYYY-MM-DD HH:mm:ss");
        item.url = item.url.split(",");
        return item;
      });
      // 把数据返回
      return { items, total: data[1] };
    } catch (error) {
      console.log(error);
      throw new InternalServerErrorException("查询失败");
    }
  }

  /**
   * 添加轮播
   * @param params 字段
   */
  async addSwiper(params: AddSwiperDto) {
    //新增轮播
    const entity = this.swiperRepository.create(params);
    const result = await this.swiperRepository.save(entity);
    if (result) {
      return "轮播创建成功";
    }
  }

  /**
   * 编辑轮播
   * @param params 字段
   */
  async editSwiper(params: EditSwiperDto) {
    const { id } = params;

    const swiper = await this.swiperRepository.findOne({ id });
    if (!swiper) {
      throw new BadRequestException("查无此轮播");
    }
    await this.swiperRepository.update(id, params);
    return "ok";
  }
}
